package com.example.easeimpro.controller.fragment;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.easeimpro.R;
import com.example.easeimpro.controller.activity.AddContactActivity;
import com.example.easeimpro.controller.activity.GroupActivity;
import com.example.easeimpro.controller.activity.NewFriendActivity;
import com.example.easeimpro.controller.activity.ShowFriendActivity;
import com.example.easeimpro.model.bean.Model;
import com.example.easeimpro.model.bean.UserInfo;
import com.example.easeimpro.model.db.Constant;
import com.example.easeimpro.utils.SpUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.interfaces.OnItemClickListener;
import com.hyphenate.easeui.interfaces.OnItemLongClickListener;
import com.hyphenate.easeui.modules.EaseBaseSetStyle;
import com.hyphenate.easeui.modules.chat.EaseChatFragment;
import com.hyphenate.easeui.modules.contact.EaseContactLayout;
import com.hyphenate.easeui.modules.contact.EaseContactListFragment;
import com.hyphenate.easeui.modules.contact.EaseContactListLayout;
import com.hyphenate.easeui.modules.conversation.EaseConversationListFragment;
import com.hyphenate.easeui.modules.conversation.EaseConversationListLayout;
import com.hyphenate.easeui.modules.conversation.model.EaseConversationSetStyle;
import com.hyphenate.easeui.modules.menu.OnPopupMenuDismissListener;
import com.hyphenate.easeui.ui.base.EaseBaseFragment;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseImageView;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

/**
 * 联系列表页面
 */
public class QunFragment extends Fragment {

    private EaseContactListLayout contactList;

    private EaseTitleBar titleBar;
    private View view;
    private Handler handler = new Handler();
    private View headerView;
    private View redItem;
    private LinearLayout friendItem;
    private LinearLayout groupItem;
    private static final String TAG = "QunFragment";
    private int res = 0,size = 0;



    private BroadcastReceiver ContactInviteChangeReceiver  = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive: 有消息 " );
            showToast("有消息");
            redItem.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);

        }
    };
    private LocalBroadcastManager mLBM;
    private List<UserInfo> contacts;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.qun_main_fragment, null, false);
        Log.e(TAG, "onCreateView: " );
        getContactFromHxServer();
        initView();
        setUpView();
        return view;
    }

  public void initView(){
       // 获取列表控件
      contactList = ((EaseContactLayout) view.findViewById(R.id.contactList)).getContactList();
        titleBar = view.findViewById(R.id.title_bar);
        titleBar.setRightImageResource(R.mipmap.add_account);
      headerView = LayoutInflater.from(getContext()).inflate(R.layout.qun_list_header_view,null,false);
      redItem = headerView.findViewById(R.id.new_red);
      friendItem = headerView.findViewById(R.id.new_friends_item);
      groupItem = headerView.findViewById(R.id.new_group_item);
  }



    public void setUpView(){

        //标题栏右侧加号按钮 点击事件
        titleBar.setOnRightClickListener(new EaseTitleBar.OnRightClickListener() {
            @Override
            public void onRightClick(View view) {
                showToast("添加联系人");
                Intent intent = new Intent(getContext(), AddContactActivity.class);
                getActivity().startActivity(intent);
            }
        });
        //联系人点击事件
        contactList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getContext(), ShowFriendActivity.class);
                intent.putExtra("itemId",position);
                intent.putExtra("conversationId",contacts.get(position-1).getHxId());
                getContext().startActivity(intent);
            }
        });
        //好友请求点击事件
        friendItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,false);
                redItem.setVisibility(View.GONE);
                nextIntent(NewFriendActivity.class);
            }
        });
        //群组按钮点击事件
        groupItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextIntent(GroupActivity.class);
            }
        });
        boolean isNewInvite = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE, false);
        redItem.setVisibility(isNewInvite?View.VISIBLE:View.GONE);//红点
        setContactListArr();
        //注册广播
        mLBM = LocalBroadcastManager.getInstance(getContext());
        mLBM.registerReceiver(ContactInviteChangeReceiver,new IntentFilter(Constant.CONTACT_INVITE_CHANGED));

        //从环信服务器 获取通讯录列表

    }
    //设置通讯录列表项的属性
    private void setContactListArr(){
        // 设置条目高度
        contactList.setItemHeight((int) EaseCommonUtils.dip2px(getContext(), 80));

// 设置条目背景
        contactList.setItemBackGround(ContextCompat.getDrawable(getContext(), R.color.white));
// 设置头像样式：0 为默认，1 为圆形，2 为方形(设置方形时，需要配合设置 avatarRadius，默认的 avatarRadius 为 50dp)
        contactList.setAvatarShapeType(EaseImageView.ShapeType.ROUND);
// 设置头像圆角
        contactList.setAvatarRadius((int) EaseCommonUtils.dip2px(getContext(), 5));
// 设置 header 背景
        contactList.setHeaderBackGround(ContextCompat.getDrawable(getContext(), R.color.white));
//添加顶部控件
        contactList.addHeaderView(headerView);
    }


    private void getContactFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                  //获取该用户所有的环信id

                          List<String> hxIds = EMClient.getInstance().contactManager().getAllContactsFromServer();
                     res =hxIds.size();
                    //校验
                    if(hxIds != null && hxIds.size() > 0){
                        //String转换为UserInfo
                        List<UserInfo> userList = new ArrayList<>();
                        for(String user : hxIds){
                            UserInfo userInfo = new UserInfo(user);
                            userList.add(userInfo);
                        }
                        //保存好友到本地服务器

                        Model.getInstance().getDbManager().getContactTableDao().saveContacts(userList,true);
                        size = Model.getInstance().getDbManager().getContactTableDao().getContacts().size();
                    //更新页面
                        if(getActivity() == null){
                            return;
                        }

                            refreshContact();


                    }
                } catch (HyphenateException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    private void refreshContact() {
        //刷新方法
        //获取数据

            Model.postHandler().post(new Runnable() {
                @Override
                public void run() {
                    contacts = Model.getInstance().getDbManager().getContactTableDao().getContacts();
                    Log.e(TAG, "refreshContact: "+ contacts.size() );
                    //校验
                    List<EaseUser> easeUsers = new ArrayList<>();

                    if(contacts != null && contacts.size()>0){

                        for(UserInfo info : contacts){
                            EaseUser user = new EaseUser();
                            user.setUsername(info.getName());
                            user.setAvatar(info.getName());
                            user.setNickname(info.getName());
                            easeUsers.add(user);
                        }
                    }
                    Log.e(TAG, "refreshList: "+easeUsers.size() );
                    contactList.setData(easeUsers);
                    contactList.refreshList();
                }
            });



    }

    @Override
    public void onStart() {
        super.onStart();

            getContactFromHxServer();


    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        //关闭广播
        mLBM.unregisterReceiver(ContactInviteChangeReceiver);
    }

    public void showToast(String msg){
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });

    }
    public void nextIntent(Class cls){
       Intent intent = new Intent(getContext(),cls);
       getContext().startActivity(intent);
    }

}
